package com.wc.alorithm_blue_bridge._前缀和与差分.卓儿砍树;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2024/4/8 23:20
 * @description https://www.lanqiao.cn/problems/17217/learning/?page=1&first_category_id=1
 */
public class Main {
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 100010;
    static int[] a = new int[N];
    static long[] s = new long[N];
    static int n;

    public static void main(String[] args) {
        n = sc.nextInt();
        for (int i = 1; i <= n; i++) a[i] = sc.nextInt();
        Arrays.sort(a, 1, n + 1);
        for (int i = 1; i <= n; i++) s[i] = s[i - 1] + a[i];
        a[0] = -1;
        long res = (long) 1e14;
        for (int i = 1; i <= n; i++) {
            // 将所有树都和当前的一样, 将前面的全砍了，如果是一样的就已经计算过了
            if (a[i] != a[i - 1]) {
                // s[n] - s[i] 就是后面所有树的高的和，(n - i) * a[i] 就是后面所有都成了a[i]
                res = Math.min(s[i - 1] + s[n] - s[i] - (long) (n - i) * a[i], res);
            }
        }
        out.println(res);
        out.flush();
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}
